const fs = require('fs')
const path = require('path')

// 所有组件名
const root = path.join(__dirname, '../../packages')
const filenames = fs.readdirSync(root)
  .filter((itemName) => fs.statSync(path.resolve(root, itemName)).isDirectory())
const noCommonUse = ['chart', 'map', 'menu', 'menuItem']
// 创建目录
const handleMkdir = (path) => {
  return new Promise((resolve, reject) => {
    fs.mkdir(path, { recursive: true }, (err) => {
      if (err) {
        throw err;
      } else {
        resolve()
      }
    });
  })
}

// 删除文件夹（递归）
const deleteFolder = (path) => {
  let files = [];
  if (fs.existsSync(path)) {
    files = fs.readdirSync(path);
    files.forEach(function (file, index) {
      let curPath = path + "/" + file;
      if (fs.statSync(curPath).isDirectory()) {
        deleteFolder(curPath);
      } else {
        fs.unlinkSync(curPath);
      }
    });
    fs.rmdirSync(path);
  }
}


// 遍历读写文件
const copyIndex = (selectFiles) => {
  selectFiles.map(async (itemName) => {
    const indexTo = path.join(__dirname, `../../zpComponents/${itemName}/index.ts`);
    const vueTo = path.join(__dirname, `../../zpComponents/${itemName}/src/${itemName}.vue`);
    const indexFrom = path.join(__dirname, `../../packages/${itemName}/index.ts`);
    const vueFrom = path.join(__dirname, `../../packages/${itemName}/src/${itemName}.vue`);

    const componentsDir = path.join(__dirname, `../../zpComponents`)
    const indexDir = path.join(__dirname, `../../zpComponents/${itemName}`);
    const vueDir = path.join(__dirname, `../../zpComponents/${itemName}/src`);

    // 创建目录
    deleteFolder(componentsDir)
     await handleMkdir(componentsDir)
     await handleMkdir(indexDir)
     fs.writeFileSync(indexTo, fs.readFileSync(indexFrom))
     await handleMkdir(vueDir)
     fs.writeFileSync(vueTo, fs.readFileSync(vueFrom))
  })
  return []
}


module.exports = plop => {
  // 创建生成器
  plop.setGenerator('zpComponents', {
    description: 'create a Source code component library',
    prompts: [{
      name: 'commonUse',
      type: 'checkbox',
      message: `总共有${filenames.length}个组件，不常用组件为${noCommonUse}`,
      choices: filenames,
      default: filenames.filter(item => !noCommonUse.includes(item))
    }], //必须有
    actions: ({ commonUse }, config, plop) => copyIndex(commonUse)
  })
}